using AutoMapper;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using ContentmanagementBase.Domain;
using ContentmanagementBaseRead.API.Applications.Commands.Departments;
using ContentmanagementBaseRead.API.Dtos;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace ContentmanagementBaseRead.API.Applications.Commandhandlters.Departments
{
    /// <summary>
    /// 获取所有科室信息命令处理
    /// </summary>
    public class GetAllDepartmentsCommandHandler : IRequestHandler<GetAllDepartmentsCommand, ApiResult<List<DepartmentDtos>>>
    {
        /// <summary>
        /// 科室仓储
        /// </summary>
        private readonly IBaseRepository<DepartmentManagementModel> _departmentRepository;
        /// <summary>
        /// 映射器
        /// </summary>
        private readonly IMapper _mapper;
        /// <summary>
        /// 日志记录器
        /// </summary>
        private readonly ILogger<GetAllDepartmentsCommandHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="departmentRepository">科室仓储</param>
        /// <param name="mapper">映射器</param>
        /// <param name="logger">日志记录器</param>
        public GetAllDepartmentsCommandHandler(
            IBaseRepository<DepartmentManagementModel> departmentRepository,
            IMapper mapper,
            ILogger<GetAllDepartmentsCommandHandler> logger)
        {
            _departmentRepository = departmentRepository;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理获取所有科室信息命令
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns></returns>
        public async Task<ApiResult<List<DepartmentDtos>>> Handle(GetAllDepartmentsCommand request, CancellationToken cancellationToken)
        {
            try
            {

                // 获取所有科室数据
                var query = _departmentRepository.GetAll().AsNoTracking();

               
                // 按创建时间倒序排列
                query = query.OrderByDescending(x => x.CreatedTime);

                // 获取数据
                var departments = await query.ToListAsync(cancellationToken);

                // 映射到DTO
                var departmentDtos = _mapper.Map<List<DepartmentDtos>>(departments);

                _logger.LogInformation("科室信息获取成功，共获取到 {Count} 个科室", departmentDtos.Count);

                return new ApiResult<List<DepartmentDtos>>
                {
                    code = ResultEnumCode.Ok,
                    message = "科室信息获取成功",
                    data = departmentDtos
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取科室信息过程中发生异常");
                return new ApiResult<List<DepartmentDtos>>
                {
                    code = ResultEnumCode.fails,
                    message = $"获取科室信息失败：{ex.Message}",
                    data = new List<DepartmentDtos>()
                };
            }
        }
    }
} 